package com.appbee.cm.client.nav.ui;

import javax.inject.Inject;

import com.appbee.cm.client.event.EditModeChange;
import com.appbee.cm.client.nav.presenter.NavAdminPresenter;
import com.appbee.core.client.design.PageStyle;
import com.appbee.core.client.ui.ToggleButton;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;

public class AdminPanel extends Composite
{
	private final FlowPanel panel = new FlowPanel();
	private final Button adminButton = new Button("Admin");
	private final ToggleButton editModeButton;
	private final EventBus eventBus;

	@Inject
	public AdminPanel(	PageStyle pageStyle,
						final AsyncProvider<NavAdminPresenter> navAdminPresenterProvider,
						final EventBus eventBus)
	{
		this.eventBus = eventBus;
		adminButton.setStyleName(pageStyle.adminButton());
		editModeButton = new ToggleButton(pageStyle.editModeButtonOn(),
				pageStyle.editModeButtonOff());
		panel.add(adminButton);
		panel.add(editModeButton);
		panel.setStyleName(pageStyle.adminPanel());
		initWidget(panel);
		adminButton.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				navAdminPresenterProvider
						.get(new AsyncCallback<NavAdminPresenter>()
						{

							@Override
							public void onSuccess(NavAdminPresenter result)
							{
								result.show();
							}

							@Override
							public void onFailure(Throwable caught)
							{
							}
						});
			}
		});
		editModeButton.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				fireEvent();
			}

		});
		Event.addNativePreviewHandler(new Event.NativePreviewHandler()
		{

			@Override
			public void onPreviewNativeEvent(NativePreviewEvent event)
			{
				NativeEvent nativeEvent = event.getNativeEvent();
				int keyCode = nativeEvent.getKeyCode();
				if (keyCode != 18)
					return;

				boolean altKey = nativeEvent.getAltKey();
				if (altKey && !editModeButton.getValue())
				{
					editModeButton.setValue(true);
					fireEvent();
				}
				else if (!altKey && editModeButton.getValue())
				{
					editModeButton.setValue(false);
					fireEvent();
				}
			}
		});
	}

	private void fireEvent()
	{
		eventBus.fireEvent(new EditModeChange(editModeButton.getValue()));
	}
}
